#include "mainwindow.h"

#include <QPushButton>
#include <QTimer>

#include "IniConfig.h"
#include "System.h"
#include "define.h"
#include "global.h"
#include "user.h"
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui_MainWindow)
{
    ui->setupUi(this);

    // 设置无边框
    // this->setWindowFlags(Qt::FramelessWindowHint);
    setFixedSize(1920, 1080);
#ifndef QT_DEBUG
    // 全屏
    this->showFullScreen();
#endif  // QT_DEBUG
    ui->lb_title->setText(IniConfigGlobal::getString(INI_KEY_STATION_NAME, "水站"));
    ui->nextAnalysisTime->setVisible(false);
    ui->nextAnalysisTime_lb->setVisible(false);
    ui->currentTask->setVisible(true);
    ui->currentTask_lb->setVisible(true);

    ui->stackedWidget->addWidget(new Home(this));
    ui->stackedWidget->addWidget(new realdata(this));
    ui->stackedWidget->addWidget(new records(this));
    ui->stackedWidget->addWidget(new operate(this));
    ui->stackedWidget->addWidget(new para_settings(this));
    sys_settings* _sysSettings = new sys_settings(this);
    ui->stackedWidget->addWidget(_sysSettings);
    user* _user = new user(this);
    ui->stackedWidget->addWidget(_user);
#ifdef QT_DEBUG
    ui->stackedWidget->addWidget(new test(this));
    QPushButton* testButton = new QPushButton("测试页面", this);
    testButton->move(200, 10);
    connect(testButton, &QPushButton::clicked, this,
            [this]() { ui->stackedWidget->setCurrentIndex(7); });
#endif  // QT_DEBUG
    // 创建菜单按钮组
    menuButtonGroup = new QButtonGroup(this);
    menuButtonGroup->setExclusive(true);
    menuButtonGroup->addButton(ui->bt_sys_status, 0);
    menuButtonGroup->addButton(ui->bt_realdata, 1);
    menuButtonGroup->addButton(ui->bt_records, 2);
    menuButtonGroup->addButton(ui->bt_operate, 3);
    menuButtonGroup->addButton(ui->bt_para_set, 4);
    menuButtonGroup->addButton(ui->bt_sys_set, 5);
    menuButtonGroup->addButton(ui->bt_user, 6);
    connect(menuButtonGroup, &QButtonGroup::idClicked, this, &MainWindow::onMenuButtonClicked);

    QTimer* timeTimer = new QTimer(this);
    connect(timeTimer, &QTimer::timeout, this, [this] {
        ui->lb_current_time->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    });
    timeTimer->start(1000);

    connect(_user, &user::currentUserChanged, this,
            [this](const QString& username) { ui->lb_current_user->setText(username); });
    connect(System::instance(), &System::infoChanged, this, [this](const SystemInfo& info) {
        ui->nextAnalysisTime->setText(info.nextAnalysisTime.toString("yyyy-MM-dd hh:mm"));
    });
    connect(System::instance(), &System::currentTaskChanged, this, [this](qint16 operateCode) {
        ui->currentTask->setText(System::instance()->getTaskName(operateCode));
    });
    connect(System::instance(), &System::isRunningChanged, this, [this](bool isRunning) {
        ui->startButton->setEnabled(!isRunning);
        ui->startButton->setText(isRunning ? "运行中..." : "启动");
        ui->nextAnalysisTime->setVisible(isRunning);
        ui->nextAnalysisTime_lb->setVisible(isRunning);
    });
    connect(_sysSettings, &sys_settings::settingsChanged, this, [this]() {
        ui->lb_title->setText(IniConfigGlobal::getString(INI_KEY_STATION_NAME, "水站"));
    });

    // 连接主题选择信号
    connect(ui->themeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
            &MainWindow::onThemeChanged);
    int themeIndex = IniConfigGlobal::getInt(INI_KEY_THEME, 0);
    // 设置主题
    ui->themeComboBox->setCurrentIndex(themeIndex);

    // 初始化通知系统
    initNotificationSystem();
    // 初始化设备错误显示
    initDevicesShowError();
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::loadStyleSheet(const QString& path)
{
    QFile file(path);
    if (file.open(QFile::ReadOnly)) {
        QString styleSheet = QLatin1String(file.readAll());
        qApp->setStyleSheet(styleSheet);
        file.close();
        qDebug() << "成功加载样式表:" << path;
    } else {
        qDebug() << "无法加载样式表文件:" << path << file.errorString();
    }
}

void MainWindow::onMenuButtonClicked(int id) { ui->stackedWidget->setCurrentIndex(id); }

void MainWindow::on_bt_exit_clicked() { close(); }

void MainWindow::closeEvent(QCloseEvent* event)
{
    int reply = QMessageBox::question(this, "退出", "确定要退出吗？", "确定", "取消");
    if (reply == 0) {
        event->accept();
    } else {
        event->ignore();
    }
}
void MainWindow::on_startButton_clicked()
{
    System* system = System::instance();
    system->start();
}

void MainWindow::on_stopButton_clicked()
{
    int reply = QMessageBox::question(this, "停止", "确定要停止所有设备吗？", "确定", "取消");
    if (reply == 0) {
        System* system = System::instance();
        system->stop();
    }
}

void MainWindow::initNotificationSystem()
{
    // 设置通知管理器的父窗口
    NotificationManager::instance()->setParentWidget(this);
}

void MainWindow::initDevicesShowError()
{
    auto deviceManager = DeviceManager::instance();
    connect(deviceManager, &DeviceManager::errorOccurred, this,
            [this](const QString& deviceName, const QString& errorMessage) {
                showError(deviceName, QString("%1").arg(errorMessage), -1);  // 永久显示
            });
    connect(deviceManager, &DeviceManager::commStatusChanged, this,
            [this](const QString& deviceName, const bool& commStatus) {
                if (!commStatus) {
                    showError(deviceName, QString("通讯失败"));
                }
            });
    connect(deviceManager, &DeviceManager::measurementOutOfRange, this,
            [this](const QString& deviceName, float value, float lowerLimit, float upperLimit) {
                showError(deviceName, QString("测量值超出设定范围: %1").arg(value, 0, 'f', 3),
                          -1);  // 永久显示
            });

    auto system = System::instance();
    connect(system, &System::taskFailed, this, [this](int taskCode, const QString& reason) {
        showError("系统", QString("任务失败: %1").arg(reason), -1);  // 永久显示
    });
}

void MainWindow::onThemeChanged(int index)
{
    QString themePath;
    QString themeName;
    switch (index) {
        case 0:  // 经典深色
            themePath = ":/qss/style.qss";
            break;
        case 1:  // 现代深色
            themePath = ":/qss/style_modern.qss";
            break;
        case 2:  // 高端黑色
            themePath = ":/qss/style_dark.qss";
            break;
        default:
            themePath = ":/qss/style.qss";
            break;
    }
    IniConfigGlobal::setInt(INI_KEY_THEME, index);
    loadStyleSheet(themePath);
}